﻿//===============================================================================
//	MapServer.h
//	地图服务器
//===============================================================================

#pragma once

#ifdef _MSC_VER
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0501
#endif
#endif

#include <unordered_map>

#include "../share/common_singleton.h"
#include "../share/server_base.h"
#include "../share/code_def.h"
#include "map_msg.h"
#include "../share/proxy_msg_mgr.h"
#include "../share/log.h"
#include "../share/server_net_new.h"
#include "../share/channel_base.h"
#include "../share/net_msg_transfer.h"

class SocketGateGame;

class CMapChannel :
	public ::common::net::CChannelBase,
	public ::common::CSingleton<CMapChannel>
{
public:
	virtual void OnMsgEvent();

	virtual void OnConnect();

	virtual void OnDisconnect();
};
class MapServer :
	public IService,
	public ::common::CSingleton<MapServer>
{
public:
	MapServer();
	~MapServer();

public:
	int32_t Initialize(void);
	int32_t Finalize();
	virtual void TickUpdate();

	int32_t client_msg_dispatch(std::string& msg, unsigned long uid, uint32_t msgId);
	virtual void client_close_socket(uint32_t uid);
	virtual void del_client_socket(uint32_t fd);
	virtual EServiceType GetServiceType() { return MAP_SERVICE; }
public:
	virtual int32_t AddClientMsg(uint32_t socketId, uint32_t msgId, std::string &msg);
	virtual void ProcessClientMsg(CClientSocketMsg& val);
	virtual int32_t ServerStart();
public:
	void RegisteClientMsg(uint32_t msg_id, MapPlayerMsgProcess fun)
	{
		map_client_msg_mgr_.RegisteMsgJson(msg_id, fun);
	}
	void RegisteServerMsg(uint32_t msg_id, ProxyMsgProcess func)
	{
		proxy_msg_mgr_.RegisteMsgJson(msg_id, func);
	}
	CMapPlayerMsgFactory& GetPlayerMsgFactory() { return map_client_msg_mgr_; }

	void SetMapGateFd(uint32_t gate_fd) { client_gate_fd = gate_fd; }
private:
	//CServerNet server_net;

	CMapPlayerMsgFactory map_client_msg_mgr_;
	common::net::CServerNet< CMapChannel > map_net_;
	int32_t client_gate_fd;
};

class SocketGateGame
	:public ::common::CSingleton<SocketGateGame>
{
public:
	SocketGateGame() {
		gate_fd_game.clear();
	}
	~SocketGateGame() {}

public:
	bool Exist(uint32_t area_id);
	uint32_t GetCurrentFd(uint32_t area_id);
	void Set(uint32_t area_id, uint32_t fd);

private:
	std::unordered_map<uint32_t, uint32_t> gate_fd_game;
};

#define registe_client_msg MapServer::GetInstance().RegisteClientMsg
#define registe_server_msg MapServer::GetInstance().RegisteServerMsg